<script setup>
	import { ref, reactive, computed, nextTick } from 'vue'
	import { message } from 'ant-design-vue'
	import { SearchOutlined, ApiOutlined } from '@ant-design/icons-vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import tool from '@/utils/tool'

	const props = defineProps({
		dataset: {
			type: Object,
			default: () => ({})
		}
	})

	const emit = defineEmits(['loadData'])

	const visible = ref(false)
	const loading = ref(false)
	const apiList = ref([])
	const searchValue = ref('')

	const indicatorForm = reactive({
		id: '',
		name: '',
		type: 'api_query',
		selectedApi: null
	})

	// 过滤后的API列表
	const filteredApiList = computed(() => {
		if (!searchValue.value) {
			return apiList.value
		}
		return apiList.value.filter(
			(api) =>
				api.path.toLowerCase().includes(searchValue.value.toLowerCase()) ||
				(api.summary && api.summary.toLowerCase().includes(searchValue.value.toLowerCase())) ||
				(api.description && api.description.toLowerCase().includes(searchValue.value.toLowerCase())) ||
				api.method.toLowerCase().includes(searchValue.value.toLowerCase())
		)
	})

	// 格式化的API选项
	const apiOptions = computed(() => {
		return filteredApiList.value.map((api) => ({
			label: `[${api.method}] ${api.path}${api.summary ? ' - ' + api.summary : ''}`,
			value: api.path,
			api: api
		}))
	})

	// 获取请求方法的颜色
	const getMethodColor = (method) => {
		const colors = {
			GET: 'green',
			POST: 'blue',
			PUT: 'orange',
			DELETE: 'red',
			PATCH: 'purple'
		}
		return colors[method] || 'default'
	}

	// 重置表单
	const resetForm = () => {
		indicatorForm.name = ''
		indicatorForm.type = 'api_query'
		indicatorForm.id = ''
		indicatorForm.selectedApi = null
		searchValue.value = ''
	}

	// 加载API接口列表
	const loadApiList = async () => {
		if (!props.dataset || !props.dataset.dataConnectorId) {
			return
		}

		try {
			loading.value = true
			const res = await dataConnectorApi.apisWithMeta({ id: props.dataset.dataConnectorId })
			// 转换API数据格式，确保包含必要的字段
			apiList.value = (res || []).map(api => ({
				path: api.apiPath || api.path,
				method: api.method || 'GET',
				summary: api.summary || api.apiDescription,
				description: api.description || api.apiDescription,
				parameters: api.parameters || []
			}))
		} catch (error) {
			console.error('获取API接口列表失败:', error)
			message.error('获取API接口列表失败')
		} finally {
			loading.value = false
		}
	}

	// 处理API选择变化
	const handleApiChange = (apiPath) => {
		const selectedApi = apiList.value.find((api) => api.path === apiPath)
		if (selectedApi) {
			indicatorForm.selectedApi = selectedApi
			// 自动填充指标名称
			if (selectedApi.summary) {
				indicatorForm.name = selectedApi.summary
			} else if (selectedApi.description) {
				indicatorForm.name = selectedApi.description
			} else {
				// 如果没有描述，使用API路径的最后一段作为名称
				const pathParts = apiPath.split('/')
				indicatorForm.name = pathParts[pathParts.length - 1] || 'API指标'
			}
		}
	}

	// 打开对话框
	const onOpen = (dataset) => {
		resetForm()
		visible.value = true
		nextTick(() => {
			loadApiList()
		})
	}

	// 关闭对话框
	const handleCancel = () => {
		resetForm()
		visible.value = false
	}

	// 保存API指标
	const handleOk = async () => {
		if (!indicatorForm.name) {
			message.error('请输入指标名称')
			return
		}

		if (!indicatorForm.selectedApi) {
			message.error('请选择API接口')
			return
		}

		try {
			loading.value = true

			// 确保数据集配置结构存在
			if (!props.dataset.config) {
				props.dataset.config = { indicators: [] }
			}
			props.dataset.config.indicators = props.dataset.config.indicators || []

			// 创建API指标配置
			const apiIndicator = {
				id: tool.snowyUuid(),
				name: indicatorForm.name,
				type: indicatorForm.type,
				datasetId: props.dataset.id,
				dataConnectorId: props.dataset.dataConnectorId,
				itemConfig: {
					apiPath: indicatorForm.selectedApi.path,
					apiMethod: indicatorForm.selectedApi.method || 'GET',
					apiParams: {},
					enableCamelCase: false,
					selectedColumns: [],
					formatConfig: [],
					columns: []
				}
			}

			// 添加到数据集配置中
			props.dataset.config.indicators.push(apiIndicator)

			// 调用接口保存
			await datasetApi.save(props.dataset)

			message.success('API指标添加成功')
			
			// 重置表单并关闭对话框
			resetForm()
			visible.value = false
			
			// 刷新左侧树结构
			emit('loadData')
		} catch (error) {
			console.error('保存API指标失败:', error)
			message.error('保存API指标失败：' + (error.message || '未知错误'))
		} finally {
			loading.value = false
		}
	}

	defineExpose({
		onOpen
	})
</script>

<template>
	<a-modal
		v-model:open="visible"
		title="添加API指标"
		:confirm-loading="loading"
		@ok="handleOk"
		@cancel="handleCancel"
		width="600px"
	>
		<a-form layout="vertical" class="mt-4">
			<a-form-item label="指标名称" required>
				<a-input 
					v-model:value="indicatorForm.name" 
					placeholder="请输入指标名称或选择API接口自动填充" 
					:disabled="loading"
				/>
			</a-form-item>

			<a-form-item label="选择API接口" required>
				<div class="space-y-3">
					<!-- 搜索框 -->
					<a-input 
						v-model:value="searchValue" 
						allow-clear 
						placeholder="搜索API接口..."
						:disabled="loading"
					>
						<template #prefix>
							<search-outlined class="text-gray-400" />
						</template>
					</a-input>

					<!-- API接口选择器 -->
					<a-select
						:filter-option="false"
						:options="apiOptions"
						:value="indicatorForm.selectedApi?.path"
						class="w-full"
						placeholder="请选择API接口"
						show-search
						:loading="loading"
						:disabled="loading"
						@change="handleApiChange"
					>
						<template #option="{ api }">
							<div class="flex items-center justify-between py-1">
								<div class="flex-1">
									<div class="flex items-center space-x-2">
										<a-tag :color="getMethodColor(api.method)" size="small">
											{{ api.method }}
										</a-tag>
										<span class="font-mono text-sm">{{ api.path }}</span>
									</div>
									<div v-if="api.summary" class="text-xs text-gray-500 mt-1">
										{{ api.summary }}
									</div>
								</div>
							</div>
						</template>
					</a-select>

					<!-- 选中API的详细信息 -->
					<div v-if="indicatorForm.selectedApi" class="p-3 bg-blue-50 rounded-lg border border-blue-200">
						<div class="space-y-2">
							<div class="flex items-center space-x-2">
								<a-tag :color="getMethodColor(indicatorForm.selectedApi.method)" size="small">
									{{ indicatorForm.selectedApi.method }}
								</a-tag>
								<span class="font-mono text-sm font-medium">{{ indicatorForm.selectedApi.path }}</span>
							</div>

							<div v-if="indicatorForm.selectedApi.summary" class="text-sm text-gray-700">
								<span class="font-medium">描述：</span>{{ indicatorForm.selectedApi.summary }}
							</div>

							<div v-if="indicatorForm.selectedApi.description && indicatorForm.selectedApi.description !== indicatorForm.selectedApi.summary" class="text-xs text-gray-600">
								{{ indicatorForm.selectedApi.description }}
							</div>

							<!-- 参数信息 -->
							<div v-if="indicatorForm.selectedApi.parameters && indicatorForm.selectedApi.parameters.length > 0" class="mt-2">
								<div class="text-xs font-medium text-gray-700 mb-1">参数：</div>
								<div class="space-y-1">
									<div
										v-for="param in indicatorForm.selectedApi.parameters"
										:key="param.name"
										class="text-xs text-gray-600 flex items-center space-x-2"
									>
										<span class="font-mono">{{ param.name }}</span>
										<span class="text-gray-400">{{ param.type }}</span>
										<span v-if="param.required" class="text-red-500">*</span>
										<span v-if="param.description" class="text-gray-500">- {{ param.description }}</span>
									</div>
								</div>
							</div>
						</div>
					</div>

					<!-- 无API接口提示 -->
					<div v-if="!loading && apiList.length === 0" class="text-center py-4 text-gray-500">
						<api-outlined class="text-2xl mb-2" />
						<div>暂无可用的API接口</div>
						<div class="text-xs mt-1">请检查连接器配置</div>
					</div>

					<!-- 搜索无结果提示 -->
					<div v-else-if="!loading && filteredApiList.length === 0 && searchValue" class="text-center py-4 text-gray-500">
						<search-outlined class="text-2xl mb-2" />
						<div>未找到匹配的API接口</div>
						<div class="text-xs mt-1">请尝试其他搜索关键词</div>
					</div>
				</div>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<style scoped>
	.ant-select {
		width: 100%;
	}

	.ant-tag {
		margin: 0;
	}
</style>
